﻿using System.Collections.Generic;
using System.Xml.Linq;

namespace MsTestUtilities.SolutionAnalysis
{
    public class PropertyGroup
    {
        private XElement _xml;
        Dictionary<string, string> _elementValueCache = new Dictionary<string, string>();
        Dictionary<string, string> _attributeValueCache = new Dictionary<string, string>();

        public PropertyGroup(XElement xml)
        {
            _xml = xml;
        }

        public bool GetBoolFromElement(string elementName, bool defaultValue = false)
        {
            var value = GetElementValue(elementName);

            if (value == null)
            {
                return defaultValue;
            }
            
            return bool.Parse(value);
        }

        public string GetAttributeValue(string attributeName)
        {
            if (!_attributeValueCache.ContainsKey(attributeName))
            {
                PopulateCacheFromAttribute(attributeName);
            }

            return _attributeValueCache[attributeName];  
        }

        public string GetElementValue(string elementName)
        {
            if (!_elementValueCache.ContainsKey(elementName))
            {
                PopulateCacheFromElement(elementName);
            }

            return _elementValueCache[elementName];            
        }

        private void PopulateCacheFromElement(string elementName)
        {
            var element = _xml.Element(MsBuildXml.Namespace + elementName);
            string value = element != null ? element.Value : null;

            _elementValueCache.Add(elementName, value);
        }

        private void PopulateCacheFromAttribute(string attributeName)
        {
            var element = _xml.Attribute(attributeName);
            string value = element != null ? element.Value : null;

            _attributeValueCache.Add(attributeName, value);
        }
    }
}
